import { AfterViewInit, Component, OnDestroy, OnInit } from '@angular/core';
import * as dayjs from 'dayjs';
import { PermitConfig, PermitConfigId } from '../../../models';
import { BaseFieldComponent } from '../base-field/base-field.component';

@Component({
  selector: 'zepride-date',
  templateUrl: './date.component.html',
  styleUrls: ['./date.component.less', '../field.common.less']
})
export class DateComponent extends BaseFieldComponent implements OnInit, AfterViewInit, OnDestroy {

  format = 'yyyy-MM-dd HH:mm:ss';
  showTime = false;
  permitConfig: PermitConfig[] = [
    { mode: 'query', permitId: '查看', permitName: '', authObjectId: '' },
    { mode: 'edit', permitId: '编辑', permitName: '', authObjectId: '' }
  ];
  isAuthorized = true;

  dateObject: {
    date?: Date;
    ts?: number;
    display?: string;
  } = {};

  ngOnInit() {
    if (this.componentData.extends.showTime != undefined) {
      this.showTime = this.componentData.extends.showTime === 'show' ? true : false;
    }
    this.format = this.getFormatStr();
    if (this.bindData) {
      if (this.bindData.ts) {
        const date = new Date(this.bindData.ts);
        this.dateChanged(date);
      }
    }
  }

  ngAfterViewInit() {
    setTimeout(() => {
      const authData = this.setAuthorityData();
      this.zeprideAuthorityData = {
        ...authData,
        afterChecked: this.afterAuthChecked.bind(this)
      };
    });
    this.registerModelChange();
  }

  getFormatStr(): string {
    let format = 'yyyy-MM-dd HH:mm:ss';
    if (this.componentData.extends.format) {
      format = this.componentData.extends.format;
      if (!this.showTime) {
        format = format.split(' ')[0];
      }
      const separator: 'cn' | '-' = this.componentData.extends.separator;
      if (separator) {
        switch (separator) {
          case 'cn':
            format = format.replace('-MM', '年MM月').replace('-dd', 'dd日');
            break;
          default:
            format = format.replace(/-/g, `${separator}`);
            break;
        }
      }
    }
    return format;
  }

  dateChanged(value: Date) {
    this.dateObject.date = value;
    if (value) {
      this.dateObject.ts = value.getTime();
      const fm = this.format.replace('yyyy', 'YYYY').replace('dd', 'DD');
      this.dateObject.display = dayjs(value).format(fm);
    }
    else {
      this.dateObject.ts = null;
      this.dateObject.display = null;
    }

    this.setBindData(this.dateObject);
  }

  setMapBindData(value) {
    const bindField: string[] = this.componentData.extends.mapField;
    if (bindField) {
      this.mapDataModel[bindField[0]] || (this.mapDataModel[bindField[0]] = {});
      this.mapDataModel[bindField[0]][bindField[1]] = value.display;
    }
  }

  registerModelChange() {
    this.modelChange$ = this.engineService.dataModelChange$.subscribe(data => {
      let componentFields = [];
      if (this.componentData.bindField) {
        componentFields = this.componentData.bindField.split('.');
      }
      if (data.identifyId !== this.componentData.identifyId && componentFields.indexOf(data.bindField) > -1) {
        this.dateObject = this.dataModel[this.componentData.bindField] ? this.dataModel[this.componentData.bindField] : {};
      }
    });
  }

  afterAuthChecked(params: {
    permitId: PermitConfigId;
    isAuthorized: boolean;
  }) {
    if (!params.isAuthorized) {
      this.isAuthorized = false;
    }
  }

  ngOnDestroy() {
    if (this.modelChange$) {
      this.modelChange$.unsubscribe();
    }
  }
}
